package queues

import (
	"context"
	"encoding/json"
	"fmt"
	"sweetsunnyflower/app/models/point"
	"sweetsunnyflower/pkg/queue"
	"sweetsunnyflower/pkg/websocket"
	"time"

	"github.com/hibiken/asynq"
	"github.com/spf13/cast"
)

type SignPayload struct {
	UserID uint64
	Point  int
	ID     uint64
}

const Sign = "sign"

func SignEvent(userID uint64, ID uint64, point int) {

	payload := SignPayload{
		UserID: userID,
		Point:  point,
		ID:     ID,
	}

	p, _ := json.Marshal(payload)

	queue.NewQueue().Run(asynq.NewTask(Sign, p), 10, time.Second*0)
}

func HandleSignTask(ctx context.Context, t *asynq.Task) error {
	var p SignPayload
	if err := json.Unmarshal(t.Payload(), &p); err != nil {
		return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry)
	}

	pointModel := &point.Point{
		UserID:      p.UserID,
		Type:        point.SignType,
		Action:      point.AddAction,
		Value:       p.Point,
		TargetID:    p.ID,
		Description: "每日签到送积分",
	}

	pointModel.Create()

	if pointModel.ID > 0 {

		point := point.Get(cast.ToString(pointModel.ID))

		websocketClient := websocket.NewClientManager()

		payload, _ := json.Marshal(point)

		con := websocket.ResponseContent{
			Action:  "sign",
			Payload: string(payload),
		}

		cc, _ := json.Marshal(con)

		if client, ok := websocketClient.ClientMap[cast.ToString(p.UserID)]; ok {
			client.SendTo(client, string(cc), websocket.TextMessage, true)
		}
	}

	return nil
}
